package com.asa.mvvm_aop_frame.basic.aspect

import android.util.Log
import com.asa.mvvm_aop_frame.basic.annotation.PermissionCheck
import com.asa.mvvm_aop_frame.basic.permission.PermissionManager
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Pointcut
import org.aspectj.lang.reflect.MethodSignature

/**
 * create By：anderson
 * on 2022/5/4
 * desc:
 */
@Aspect
class PermissionAspect {


    @Pointcut("execution(@com.asa.mvvm_aop_frame.basic.annotation.PermissionCheck * *(..))")
    private fun permissionCheck(){

    }


    @Around("permissionCheck()")
    fun aroundJoinAspectPermissionCheck(joinPoint: ProceedingJoinPoint){
        val methodSignature = joinPoint.signature as MethodSignature
        val annotation = methodSignature.method.getAnnotation(PermissionCheck::class.java)
        if (annotation != null && annotation.permissions.isNotEmpty()){
            PermissionManager
                .permission(* annotation.permissions)
                .callBack(object :PermissionManager.SimpleCallback{
                    override fun onGranted() {
                        joinPoint.proceed()
                    }

                    override fun onDenied() {
                        Log.e("日志", "onDenied: 拒绝了权限")
                        if (annotation.deniedMethod.isNotEmpty()){
                            val declaredMethod =
                                joinPoint.target.javaClass.getDeclaredMethod(annotation.deniedMethod)
                            declaredMethod.isAccessible = true
                            declaredMethod.invoke(joinPoint.target)
                        }

                    }

                })
                .request()
            Log.e("日志", "aroundJoinAspectPermissionCheck: 获取到权限参数")
        } else{
            joinPoint.proceed()
        }
    }

}